package com.hup.utils.commons;

import lombok.extern.log4j.Log4j2;

import java.lang.ref.WeakReference;

/**
 * @author hugan
 * @date 2020/1/10
 */
@Log4j2
public class WeakReferenceUtil<T> {

    private WeakReference<T> weakReference;
    private final Initer<T> initer;

    public WeakReferenceUtil(Initer<T> initer) {
        this.initer = initer;
    }

    public T get() {
        T res;
        if (weakReference == null || (res = weakReference.get()) == null) {
            log.debug("首次初始化={}, 回收后重新加载={}", weakReference == null, weakReference != null);
            res = initer.get();
            weakReference = new WeakReference<>(res);
        }
        return res;
    }

    public interface Initer<T> {
        T get();
    }

}
